package com.dyc.course.sys.service.impl;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dyc.course.sys.entity.SysUserEntity;
import com.dyc.course.sys.repository.SysUserRepository;
import com.dyc.course.sys.service.SysUserRoleService;
import com.dyc.course.sys.service.SysUserService;
import com.dyc.course.sys.shiro.ShiroUtils;

import java.util.Date;

/**
 * 系统用户
 *
 */
@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserRepository repository;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveUser(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setSalt(salt);
		user.setPassword(ShiroUtils.sha256(user.getPassword(), user.getSalt()));
		repository.save(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysUserEntity user) {
		if (StringUtils.isBlank(user.getPassword())) {
			user.setPassword(null);
		} else {
			SysUserEntity userEntity = repository.getOne(user.getUserId());
			user.setPassword(ShiroUtils.sha256(user.getPassword(), userEntity.getSalt()));
		}
		repository.save(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity entity = repository.getOne(userId);
        if (password.equals(entity.getPassword())) {
        	entity.setPassword(newPassword);
        	repository.save(entity);
        	return true;
        }
        return false;
    }

}
